<template>
  <div class="building-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <div class="search-label">企业名称：</div>
      <el-input
        clearable
        placeholder="请输入内容"
        class="search-main"
        v-model="params.name"
      />
      <el-button type="primary" @click="doSearch">查询</el-button>
    </div>

    <div class="create-container">
      <el-button
        type="primary"
        @click="addData"
        v-auth-btn="'park:enterprise:add_edit'"
        >添加企业</el-button
      >
    </div>

    <!-- 表格区域 -->
    <div class="table">
      <el-table style="width: 100%" :data="rows" @expand-change="handerExpand"> 
        <el-table-column type="expand">
          <template #default="scope">
            <el-table :data="scope.row.rentList">
              <el-table-column
                label="租赁楼宇"
                width="320"
                prop="buildingName"
              />
              <el-table-column label="租赁起始时间" prop="startTime" />
              <el-table-column label="租赁结束时间" prop="endTime" />
              <el-table-column label="合同状态" prop="status">
                <template #default="scope">
                  <el-tag :type="formatInfoType(scope.row.status)">
                    {{ formartStatus(scope.row.status) }}
                  </el-tag>
                </template>
              </el-table-column>
              <el-table-column label="操作" width="180">
                <template #default="scope">
                  <el-button size="mini" type="text">续租</el-button>
                  <el-button
                    size="mini"
                    type="text"
                    @click="reRentSubmit(scope.row.id)"
                    :disabled="scope.row.status === 3"
                    >退租</el-button
                  >
                  <el-button
                    size="mini"
                    type="text"
                    :disabled="scope.row.status !== 3"
                    @click="deleteRent(scope.row.id)"
                    >删除</el-button
                  >
                </template>
              </el-table-column>
            </el-table>
          </template>
        </el-table-column>
        <el-table-column type="index" label="序号" prop="id" width="60" />
        <el-table-column label="企业名称" width="320" prop="name" />
        <el-table-column label="联系人" prop="contact" />
        <el-table-column label="联系电话" prop="contactNumber" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              size="mini"
              type="text"
              @click="addContract(scope.row.id)"
              v-auth-btn="'park:rent:add_surrender'"
              >添加合同</el-button
            >
            <el-button
              size="mini"
              type="text"
              @click="editData(scope.row.id)"
              v-auth-btn="'park:enterprise:query'"
              >查看</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="EditData(scope.row.id)"
              v-auth-btn="'park:enterprise:add_edit'"
              >编辑</el-button
            >

            <el-button
              size="mini"
              type="text"
              @click="DeleteData(scope.row.id)"
              v-auth-btn="'park:enterprise:remove'"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-container">
      <el-pagination
        :current-page="params.page"
        :page-size="params.pageSize"
        :total="total"
        :page-sizes="pageSizes"
        background
        layout="total,sizes, prev, pager, next"
        @current-change="handleCurrentChange"
        @size-change="handleSizeChange"
      />
    </div>

    <el-dialog :title="title" width="580px" :visible="isshow" @close="close">
      <div class="form-container">
        <el-form
          :model="addForm"
          :rules="addRules"
          label-width="100px"
          ref="ruleForm"
        >
          <el-form-item label="企业名称" prop="name">
            <el-input v-model="addForm.name" />
          </el-form-item>

          <el-form-item label="法人" prop="legalPerson">
            <el-input v-model="addForm.legalPerson" />
          </el-form-item>

          <el-form-item label="注册地址" prop="registeredAddress">
            <el-input v-model="addForm.registeredAddress" />
          </el-form-item>

          <el-form-item label="所在行业" prop="industryCode">
            <el-select v-model="addForm.industryCode">
              <el-option
                v-for="item in industryList"
                :key="item.industryCode"
                :label="item.industryName"
                :value="item.industryCode"
              ></el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="企业联系人" prop="contact">
            <el-input v-model="addForm.contact" />
          </el-form-item>

          <el-form-item label="联系电话" prop="contactNumber">
            <el-input v-model="addForm.contactNumber" />
          </el-form-item>

          <el-form-item label="营业执照" prop="businessLicenseId">
            <el-upload
              ref="upload"
              action="#"
              :before-upload="beforeUpload"
              :http-request="uploadRequest"
            >
              <el-button size="small" type="primary">点击上传</el-button>
              <div slot="tip" class="el-upload__tip">
                支持扩展名：.png .jpg .jpeg，文件大小不得超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button type="danger" @click="close">取 消</el-button>
        <el-button type="primary" @click="confirmSubmit">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog
      title="添加合同"
      :visible="rentDialogVisible"
      width="580px"
      @close="RentClose"
    >
      <div class="form-container">
        <el-form
          ref="rentFormList"
          :model="rentForm"
          :rules="rentRules"
          label-position="top"
        >
          <el-form-item label="租赁楼宇" prop="buildingId">
            <el-select v-model="rentForm.buildingId" placeholder="请选择">
              <el-option
                v-for="item in rentBuildList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <el-form-item label="租赁起止日期" prop="rentTime">
            <el-date-picker
              v-model="rentForm.rentTime"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              value-format="yyyy-MM-dd"
            />
          </el-form-item>

          <el-form-item label="租赁合同" prop="contractId">
            <el-upload action="#" :http-request="uploadHandle" ref="upload">
              <el-button size="small" type="primary" plain
                >上传合同文件</el-button
              >

              <div slot="tip" class="el-upload__tip">
                支持扩展名：.doc .docx .pdf, 文件大小不超过5M
              </div>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <el-button @click="RentClose">取 消</el-button>
        <el-button type="primary" @click="rentSubmit">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import {
  EnterpriseList,
  getIndustryListAPI,
  createExterpriseAPI,
  uploadAPI,
  expandListAPI,
  getEnterpriseDetailAPI,
  updateExterpriseAPI,
  deleteExterpriseAPI,
  getrentbuildListAPI,
  getrentbuildDetailAPI,
  getreturnDetailAPI,
  DeleterRentAPI,
} from "@/api/enterprise";
export default {
  name: "Building",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (/^1[3-9]\d{9}$/.test(value)) {
        callback();
      } else {
        callback(new Error("请输入正常的手机号"));
      }
    };
    return {
      total: 0,
      id: "",
      pageSizes: [5, 10, 20, 30],
      industryList: [],
      rows: [],
      rentBuildList: [],
      isshow: false,
      rentDialogVisible: false,
      title: "",
      params: {
        page: 1,
        pageSize: 10,
        name: "",
      },
      addForm: {
        name: "", //企业名称
        legalPerson: "",
        registeredAddress: "", //注册地址
        industryCode: "", //所在行业
        contact: "", //企业联系人
        contactNumber: "", //企业联系人电话
        businessLicenseUrl: "", //营业执照Url
        businessLicenseId: "", //营业执照id
      },
      addRules: {
        name: [{ required: true, message: "企业名称为必填", trigger: "blur" }],
        legalPerson: [
          { required: true, message: "法人为必填", trigger: "blur" },
        ],

        registeredAddress: [
          { required: true, message: "注册地址为必填", trigger: "blur" },
        ],
        industryCode: [
          { required: true, message: "所在行业为必填", trigger: "change" },
        ],
        contact: [
          { required: true, message: "企业联系人为必填", trigger: "blur" },
        ],
        contactNumber: [
          { required: true, message: "企业联系人电话为必填", trigger: "blur" },
          { validator: validatePhone, trigger: "blur" },
        ],
        businessLicenseId: [
          { required: true, message: "请上传营业执照", trigger: "blur" },
        ],
      },
      rentForm: {
        buildingId: null, // 楼宇id
        contractId: null, // 合同id
        contractUrl: "", // 合同Url
        enterpriseId: null, // 企业id
        type: 0, // 合同类型
        rentTime: [], // 合同时间
      },
      rentRules: {
        buildingId: [
          { required: true, message: "请选择楼宇", trigger: "change" },
        ],
        rentTime: [
          { required: true, message: "请选择租赁日期", trigger: "change" },
        ],
        contractId: [{ required: true, message: "请上传合同文件" }],
      },
    };
  },
  created() {
    this.getEnterpriseList();
  },

  methods: {
    async getEnterpriseList() {
      const { data } = await EnterpriseList(this.params);
      this.total = data.total;
      this.rows = data.rows.map((item) => {
        return { ...item, rentList: [] };
      });
    },
    doSearch() {
      this.getEnterpriseList();
    },
    handleCurrentChange(current) {
      this.params.page = current;
      this.getEnterpriseList();
    },
    handleSizeChange(size) {
      this.params.pageSize = size;
      this.getEnterpriseList();
    },
    close() {
      this.isshow = false;
      this.$refs.ruleForm.resetFields();
      this.$refs.upload.clearFiles();
    },
    RentClose() {
      this.rentDialogVisible = false;
      this.$refs.rentFormList.resetFields();
      this.$refs.upload.clearFiles();
    },
    getIndustryList() {
      getIndustryListAPI().then((res) => {
        this.industryList = res.data;
      });
    },
    confirmSubmit() {
      this.$refs.ruleForm.validate(async (valid) => {
        if (!valid) return;
        if (this.title === "添加企业") {
          try {
            let res = await createExterpriseAPI(this.addForm);
            this.$message.success(res.msg);
          } catch (e) {
            this.$message.error(e.msg);
          }
        } else if (this.title === "编辑企业") {
          const data = { ...this.addForm, id: this.id };
          let res = await updateExterpriseAPI(data);
          this.$message.success(res.msg);
        }
        this.getEnterpriseList();
        this.close();
      });
    },
    // 上传营业执照图片校验
    beforeUpload(file) {
      const allowImgType = ["image/jpeg", "image/png", "image/jpg"].includes(
        file.type
      );

      const isLt5M = file.size / 1024 / 1024 < 5;

      if (!allowImgType) {
        this.$message.error("上传合同图片只能是 PNG/JPG/JPEG 格式!");
      }
      if (!isLt5M) {
        this.$message.error("上传合同图片大小不能超过 5MB!");
      }
      return allowImgType && isLt5M;
    },
    // 上传营业执照
    async uploadRequest(data) {
      const file = data.file;
      // 处理formData类型参数
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "businessLicense");
      const res = await uploadAPI(formData);
      // 赋值表单数据
      this.addForm.businessLicenseId = res.data.id;
      this.addForm.businessLicenseUrl = res.data.url;
      // 单独校验表单，清除错误信息
      this.$refs.ruleForm.validateField("businessLicenseId");
    },

    // 上传合同
    async uploadHandle(fileData) {
      // 1. 处理FormData
      const { file } = fileData;
      const formData = new FormData();
      formData.append("file", file);
      formData.append("type", "contract");
      // 2. 上传并赋值
      const res = await uploadAPI(formData);
      const { id, url } = res.data;
      this.rentForm.contractId = id;
      this.rentForm.contractUrl = url;
      // 单独校验表单
      this.$refs.rentFormList.validateField("contractId");
    },
    // 展开行 请求租赁楼宇列表
    async handerExpand(row, expandedRows) {
      // 判断是否展开,展开才请求数据
      const isExpend = expandedRows.find((item) => item.id === row.id);
      console.log(row, expandedRows);
      if (!isExpend) return;
      let res = await expandListAPI(row.id);
      row.rentList = res.data;
      console.log(row.rentList);
    },
    formatInfoType(status) {
      const MAP = {
        0: "warning",
        1: "success",
        2: "info",
        3: "danger",
      };
      // return 格式化之后的中文显示
      return MAP[status];
    },
    formartStatus(type) {
      //中括号取值法
      const TYPEMAP = {
        0: "待生效",
        1: "生效中",
        2: "已到期",
        3: "已退租",
      };
      return TYPEMAP[type];
    },
    addData() {
      this.isshow = true;
      this.title = "添加企业";
      this.getIndustryList();
    },
    EditData(id) {
      this.isshow = true;
      this.title = "编辑企业";
      getEnterpriseDetailAPI(id).then((res) => {
        this.id = id;
        this.addForm = res.data;
        delete this.addForm.rent;
        delete this.addForm.businessLicenseName;
        delete this.addForm.industryName;
      });
    },
    DeleteData(id) {
      this.$confirm("确认删除该企业吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await deleteExterpriseAPI(id);
          this.$message.success(res.msg);
          this.getEnterpriseList();
        })
        .catch((e) => {
          this.$message.info("已取消操作");
        });
    },
    addContract(id) {
      this.rentDialogVisible = true;
      this.getrentbuildList();
      this.rentForm.enterpriseId = id;
    },
    getrentbuildList() {
      getrentbuildListAPI().then((res) => {
        this.rentBuildList = res.data;
      });
    },
    rentSubmit() {
      this.$refs.rentFormList.validate(async (valid) => {
        if (!valid) return;
        try {
          const data = {
            ...this.rentForm,
            startTime: this.rentForm.rentTime[0],
            endTime: this.rentForm.rentTime[1],
          };
          delete data.rentTime;
          console.log(data);
          let res = await getrentbuildDetailAPI(data);
          this.$message.success(res.msg);
        } catch (e) {
          this.$message.error(e.msg);
        }
        this.getEnterpriseList();
        this.RentClose();
      });
    },
    reRentSubmit(id) {
      this.$confirm("确认退租吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await getreturnDetailAPI(id);
          this.getEnterpriseList();
          this.$message.success("退租成功");
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    deleteRent(id) {
      this.$confirm("确认删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(async () => {
          let res = await DeleterRentAPI(id);
          this.$message.success("删除成功");
          this.getEnterpriseList();
        })
        .catch(() => {
          this.$message.info("已取消操作");
        });
    },
    editData(id) {
      this.$router.push({
        path: "/exterpriseDetail",
        query: { id },
      });
    },
  },
  watch: {
    "params.name"(newVal, oldVal) {
      if (!newVal) {
        this.getEnterpriseList();
      }
    },
    deep: true,
  },
};
</script>

<style lang="scss" scoped>
.department-container {
  padding: 10px;
}

.search-container {
  display: flex;
  align-items: center;
  border-bottom: 1px solid rgb(237, 237, 237, 0.9);
  padding-bottom: 20px;

  .search-label {
    width: 100px;
  }

  .search-main {
    width: 220px;
    margin-right: 10px;
  }
}
.create-container {
  margin: 10px 0px;
}
.page-container {
  padding: 4px 0px;
  text-align: right;
}
.form-container {
  padding: 0px 80px;
}
</style>